package com.next

class Account
{
    String name
    String alias
    //曾用名

    AccountType type

    Boolean active = true

    AccountLevel level

    String website
    Integer numberOfEmployees = 0
    Double registeredCapital = 0
    //注册资本（元）
    CurrencyType currencyType
    Country country
    City city

    String externalId

    User createBy
    User modifyBy
    User user

    Date createdDate = new Date()
    Date modifiedDate = new Date()

    Lead lead

    Account parent

    String description

    Territory territory

    Industry industry

    // static hasMany = [addresses: Address, notes: Note, attachments: Attachment, activities: Activity, users: AccountTeam]
    static hasMany = [addresses: Address, notes: Note, attachments: Attachment, activities: Activity, users: AccountTeam, contacts: Contact]

    static constraints = {
        name maxSize: 64, unique: true
        alias maxSize: 64, blank: true, nullable: true

        parent blank: true, nullable: true

        externalId maxSize: 32, blank: true, nullable: true //, unique: true

        lead blank: true, nullable: true

        website blank: true, nullable: true, maxSize: 256, url: true

        description blank: true, nullable: true, type: "text"

        createBy nullable: true, blank: true
        modifyBy nullable: true, blank: true
        user nullable: true, blank: true

        createdDate nullable: true, blank: true
        modifiedDate nullable: true, blank: true

        level nullable: true, blank: true
        territory nullable: true, blank: true

        registeredCapital nullable: true, blank: true

        // industry nullable: true, blank: true
        currencyType nullable: true, blank: true
        country nullable: true, blank: true
        city nullable: true, blank: true
    }

    static mapping = {
        sort 'name'
    }

    def springSecurityService

    def beforeInsert()
    {
        def username = springSecurityService?.getPrincipal()?.username
        createBy = User.findByUsername(username)
        if (!user)
        {
            user = createBy
        }

        // 初始化 区域用户 权限
        if (territory)
        {
            def territoryTeam = TerritoryTeam.findAllByTerritory(territory)
            territoryTeam?.each {
                def accountTeam = new AccountTeam(account: this, user: it.user, teamRole: it.teamRole,
                                                  contactPermission: it?.contactPermission,
                                                  activityPermission: it?.activityPermission,
                                                  teamPermission: it?.teamPermission,
                                                  attachmentPermission: it?.attachmentPermission,
                                                  notePermission: it?.notePermission,
                                                  flexFieldPermission: it?.flexFieldPermission,
                                                  addressPermission: it?.addressPermission)
                this.addToUsers(accountTeam)
            }
        }

        // 初始化 上级用户 权限
        if (user?.shareAccountToSupervisor)
        {
            User reportTo = user.reportTo

            while (reportTo)
            {

                def flag = true
                users?.each {
                    if (reportTo == it?.user)
                    {
                        flag = false
                    }
                }

                if (flag)
                {
                    AccountTeam accountTeam = new AccountTeam(account: this, user: reportTo, teamRole: TeamRole.findByName('Read'),
                                                              contactPermission: TeamRole.findByName('Read'),
                                                              activityPermission: TeamRole.findByName('Read'),
                                                              teamPermission: TeamRole.findByName('Read'),
                                                              attachmentPermission: TeamRole.findByName('Read'),
                                                              notePermission: TeamRole.findByName('Read'),
                                                              flexFieldPermission: TeamRole.findByName('Read'),
                                                              addressPermission: TeamRole.findByName('Read'))
                    this.addToUsers(accountTeam)
                }

                reportTo = reportTo.reportTo
            }
        }

        // 初始化 所有者 权限
        def flag = true
        users?.each {
            if (user == it?.user)
            {
                flag = false
            }
        }

        if (flag)
        {
            AccountTeam accountTeam = new AccountTeam(account: this,
                                                      user: user,
                                                      teamRole: TeamRole.findByName('Edit'),
                                                      contactPermission: TeamRole.findByName('Edit'),
                                                      activityPermission: TeamRole.findByName('Edit'),
                                                      teamPermission: TeamRole.findByName('Edit'),
                                                      attachmentPermission: TeamRole.findByName('Edit'),
                                                      notePermission: TeamRole.findByName('Edit'),
                                                      flexFieldPermission: TeamRole.findByName('Edit'),
                                                      addressPermission: TeamRole.findByName('Edit'))
            this.addToUsers(accountTeam)
        }
    }

    def afterInsert()
    {
        def flexFieldCategories = FlexFieldCategory.findAllByObjectType('Account')
        flexFieldCategories?.each {
            if (it?.condition)
            {
                def result = false
                try
                {
                    def shell = new GroovyShell()
                    def closure = shell.evaluate(it?.condition?.script)
                    result = closure(this)
                }
                catch (Exception e)
                {
                    log.error e
                }
                if (result)
                {
                    initFlexField(it)
                }
            }
            else
            {
                initFlexField(it)
            }
        }
    }

    def initFlexField(FlexFieldCategory flexFieldCategory)
    {
        def fields = FlexField.findAllByCategory(flexFieldCategory)
        fields?.each {
            def field = new FlexFieldInstance(category: flexFieldCategory, field: it, account: this)
            field.save()
        }
    }

    def beforeUpdate()
    {
        modifiedDate = new Date()
        def username = springSecurityService?.getPrincipal()?.username
        modifyBy = User.findByUsername(username)

        // 初始化 所有者 权限
        def flag = true
        users?.each {
            if (user == it?.user)
            {
                flag = false
            }
        }

        if (flag)
        {
            AccountTeam accountTeam = new AccountTeam(account: this,
                                                      user: user,
                                                      teamRole: TeamRole.findByName('Edit'),
                                                      contactPermission: TeamRole.findByName('Edit'),
                                                      activityPermission: TeamRole.findByName('Edit'),
                                                      teamPermission: TeamRole.findByName('Edit'),
                                                      attachmentPermission: TeamRole.findByName('Edit'),
                                                      notePermission: TeamRole.findByName('Edit'),
                                                      flexFieldPermission: TeamRole.findByName('Edit'),
                                                      addressPermission: TeamRole.findByName('Edit'))
            this.addToUsers(accountTeam)
        }
    }

    String toString()
    {
        name
    }
}
